package fr.utbm.gl52.smartgrid.controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.ref.WeakReference;
import java.util.UUID;

import fr.utbm.gl52.smartgrid.model.BusDC;
import fr.utbm.gl52.smartgrid.model.ModelManager;
import fr.utbm.gl52.smartgrid.util.Constants;

public class Controller implements ActionListener {

	private WeakReference<BusDC> model;
	private WeakReference<ModelManager> modelManager;

	public int getNextDeviceID() {
		return this.model.get().getNbDevices();
	}

	public Controller() {
	}

	public void setModelManager(ModelManager _modelManager) {
		this.modelManager = new WeakReference<ModelManager>(_modelManager);
	}

	@Override
	public void actionPerformed(ActionEvent event) {
		String command = event.getActionCommand();
		if (Constants.isDebug)
			System.out.println("Controller " + event.getActionCommand()); //$NON-NLS-1$

		if (command.startsWith(Constants.PREFIX_REQUEST)) {
			command = command.substring(Constants.PREFIX_REQUEST.length()); // device
																		// index
			if (Constants.isDebug)
				System.out.println("Controller_edit " //$NON-NLS-1$
					+ event.getActionCommand() + " " + command); //$NON-NLS-1$
			
			this.modelManager.get().requestDevice(UUID.fromString(command));
		} else if (command.startsWith(Constants.PREFIX_CREATE)) {
			String tmp = command.substring(6, command.length());
			this.modelManager.get().addDevice(tmp);

			if (Constants.isDebug)
				System.out.println("Controller_create " //$NON-NLS-1$
						+ event.getActionCommand());
		} else if (command.startsWith(Constants.PREFIX_DELETE)) {
			String tmp = command.substring(Constants.PREFIX_DELETE.length());

			this.modelManager.get().removeDevice(UUID.fromString(tmp));

			if (Constants.isDebug)
				System.out.println("Controller_delete " //$NON-NLS-1$
						+ event.getActionCommand());
		}

		else if (command.startsWith(Constants.PREFIX_CREATEPPTPANEL)) {
			String className = command
					.substring(Constants.PREFIX_CREATEPPTPANEL.length());


			this.modelManager.get().addDevice(className);
		}

		else if (command.startsWith(Constants.PREFIX_VALIDATEPPEP)) {
			this.modelManager.get().modifyDevice();
		}
	}
}
